package com.coolw.data.migrate.process.strategy;

import com.coolw.data.migrate.common.constant.SqlTemplateConst;
import com.coolw.data.migrate.domain.request.DataMigrateRequest;
import com.coolw.data.migrate.domain.response.DataMigrateResponse;
import com.coolw.data.migrate.enums.MigrateTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.date.DateFormatPool;
import org.dromara.hutool.core.date.DateTime;
import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * 按日期范围迁移（包含开始日期和结束日期）
 *
 * @author coolw
 * @date 2024/2/1 15:19
 */
@Slf4j
@Component
public class BetweenDateMigrateProcess extends AbstractDataMigrateProcess {

    @Override
    public MigrateTypeEnum type() {
        return MigrateTypeEnum.BETWEEN_DATE;
    }

    @Override
    public DataMigrateResponse process(DataMigrateRequest req) {
        String startDate = req.getStartDate();
        if (StrUtil.isBlank(startDate)) {
            return DataMigrateResponse.fail("startDate 不能为空");
        }

        String endDate = req.getEndDate();
        if (StrUtil.isBlank(endDate)) {
            return DataMigrateResponse.fail("endDate 不能为空");
        }

        DateTime startDateTime = DateUtil.parse(startDate, DateFormatPool.NORM_DATE_PATTERN);
        DateTime endDateTime = DateUtil.parse(endDate, DateFormatPool.NORM_DATE_PATTERN);
        int compare = DateUtil.compare(endDateTime, startDateTime);
        if (compare < 0) {
            return DataMigrateResponse.fail("endDate不能早于startDate");
        }

        return doProcess(req);
    }

    @Override
    public List<String> getDataMigrateSql(DataMigrateRequest req) {
        return getLastDataMigrateSql(req, perBatchLimit);
    }

    @Override
    public List<String> getLastDataMigrateSql(DataMigrateRequest req, long lastBatchSize) {
        String targetTableName = req.getTargetTableName();
        String sourceTableName = req.getSourceTableName();
        String startDate = req.getStartDate();
        String endDate = req.getEndDate();

        String insertSql = StrUtil.format(SqlTemplateConst.BetweenDateEnum.INSERT_SQL_TEMPLATE.getSql(), targetTableName, sourceTableName, startDate, endDate, lastBatchSize);
        String deleteSql = StrUtil.format(SqlTemplateConst.BetweenDateEnum.DELETE_SQL_TEMPLATE.getSql(), sourceTableName, startDate, endDate, lastBatchSize);
        return Arrays.asList(insertSql, deleteSql);
    }

    @Override
    public String getCountSql(DataMigrateRequest req) {
        String sourceTableName = req.getSourceTableName();
        String startDate = req.getStartDate();
        String endDate = req.getEndDate();
        return StrUtil.format(SqlTemplateConst.BetweenDateEnum.COUNT_SQL_TEMPLATE_WITH_CONDITION.getSql(), sourceTableName, startDate, endDate);
    }
}
